package com.penjin.android.activity.map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.easemob.util.NetUtils;
import com.penjin.android.R;
import com.penjin.android.constants.PenjinConstants;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.LocationInfoView;
import com.penjin.android.view.TitleBarView;

import java.util.Date;
import java.util.Locale;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Administrator on 2016/4/14.
 */
public class MapAddressPickerActivity extends Activity implements View.OnClickListener {
    TitleBarView titleBarView;
    MapView mMapView;
    BaiduMap mBaiduMap;

    CustomProgressDialog progressDialog;
    private boolean isLocated = false;
    private BDLocation bdLocation;
    private int locationRetryTimes = 5;
    private LocationClient mLocationClient = null;
    private Date lastLocateDate;
    private BDLocationListener mLocationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            boolean locationResult = false;
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                locationResult = true;
                lastLocateDate = new Date();
                bdLocation = location;
                refreshLocationUi();
            }
            if (locationResult == true) {
                mLocationClient.stop();
                isLocated = true;
            } else {
                locationRetryTimes--;
                System.out.println("定位重试次数剩余：" + locationRetryTimes);
                if (locationRetryTimes == 0) {
                    isLocated = false;
                    mLocationClient.stop();//表示这次定位请求失败
                }
            }
        }
    };

    private View ok;
    private LocationInfoView locationInfo;
    private GeoCoder geoCoder;
    private View searchBtn;
    private EditText search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_address_picker);
        initView();
        initMap();
        initLocation();
    }

    private void initView() {
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        locationInfo = (LocationInfoView) findViewById(R.id.locationInfo);
        ok = findViewById(R.id.ok);
        ok.setOnClickListener(this);
        searchBtn = findViewById(R.id.searchBtn);
        searchBtn.setOnClickListener(this);
        search = (EditText) findViewById(R.id.search);
    }

    private void initMap() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                progressDialog.dismiss();
                LatLng ll = geoCodeResult.getLocation();
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(mapStatusUpdate);
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                locationInfo.setInfo(reverseGeoCodeResult.getAddress());
            }
        });
        mMapView = (MapView) findViewById(R.id.mapView);
        mBaiduMap = mMapView.getMap();
        int childCount = mMapView.getChildCount();
        View zoom = null;
        for (int i = 0; i < childCount; i++) {

            View child = mMapView.getChildAt(i);

            if (child instanceof ZoomControls) {
                zoom = child;
                break;
            }
        }
        zoom.setVisibility(View.GONE);
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                LatLng target = mapStatus.target;
                ReverseGeoCodeOption option = new ReverseGeoCodeOption();
                option.location(target);
                geoCoder.reverseGeoCode(option);
            }
        });
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(mLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    /**
     * 更新UI上的位置信息
     */
    private void refreshLocationUi() {
        mBaiduMap.setMyLocationEnabled(true);
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                .direction(100).latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);
       /* MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.COMPASS, true, null);
        mBaiduMap.setMyLocationConfigeration(config);
        mBaiduMap.clear();*/
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
        // 当不需要定位图层时关闭定位图层
        mBaiduMap.animateMapStatus(msu);
        locationInfo.setInfo(bdLocation.getAddrStr());
    }

    private void startLocation() {
        if (!NetUtils.hasNetwork(this)) {
            Toast.makeText(this, "定位前，需开启您的网络~", Toast.LENGTH_SHORT).show();
            return;
        }
        isLocated = false;
        locationRetryTimes = 5;
        mLocationClient.start();
    }

    @Override
    protected void onResume() {
        if (mMapView != null)
            mMapView.onResume();
        if (mLocationClient != null && isLocated == false) {
            startLocation();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mLocationClient != null)
            mLocationClient.stop();
        if (mMapView != null)
            mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("YidiActivity:onDestroy");
        PenjinConstants.currentBitmaps = null;
        if (mLocationClient != null) {
            if (mLocationListener != null)
                mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient = null;
        }
        if (mMapView != null)
            mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                Intent intent = new Intent();
                intent.putExtra("address", locationInfo.getInfo());
                setResult(1, intent);
                finish();
                break;
            case R.id.searchBtn:
                if (HttpUtil.isNetworkAvailable(this)) {
                    String toSearchStr = search.getEditableText().toString();
                    if (toSearchStr != null && !toSearchStr.equals("")) {
                        progressDialog.show();
                        GeoCodeOption geoCodeOption = new GeoCodeOption();
                        geoCodeOption.city(toSearchStr);
                        geoCodeOption.address(toSearchStr);
                        geoCoder.geocode(geoCodeOption);
                    }
                } else {
                    ToastHelper.showNoNetwork(this);
                }

                break;
        }
    }
}
